package com.projectsexception.festivales;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.projectsexception.festivales.provider.Downloader;
import com.projectsexception.festivales.provider.exceptions.ParserException;
import com.projectsexception.festivales.setup.ConfigurationException;
import com.projectsexception.festivales.setup.ProjectResources;

public class SetupActivity extends Activity {
    
    private static final String URL_SERVER = "http://10.240.0.4/festivales/";
    
    protected ProgressDialog mProgressDialog;
    private static SetupTask task;
    
    private class SetupTask extends AsyncTask<Void, Integer, Boolean> {
        
        private SetupActivity activity;
        
        public void setActivity(SetupActivity activity) {
            this.activity = activity;
        }
        
        @Override
        protected void onPreExecute() {
            activity.showDialog(0);
        }

        @Override
        protected Boolean doInBackground(Void... voids) {            
            try {
                ProjectResources res = ProjectResources.initialize(activity, "2011/sonisphere/es");
                File appDir = res.getXMLDir();
                Downloader downloader = new Downloader();
                downloader.dowloadFile(new File(appDir, ProjectResources.INFO_FILE), URL_SERVER + ProjectResources.INFO_FILE);
                publishProgress(0);
                res.loadInfos();
                publishProgress(10);
                downloader.dowloadFile(new File(appDir, ProjectResources.MAPS_FILE), URL_SERVER + ProjectResources.MAPS_FILE);
                publishProgress(15);
                res.loadMaps();
                publishProgress(20);
                downloader.dowloadFile(new File(appDir, ProjectResources.FEEDS_FILE), URL_SERVER + ProjectResources.FEEDS_FILE);
                publishProgress(30);
                res.loadFeeds();
                publishProgress(40);
                downloader.dowloadFile(new File(appDir, ProjectResources.STAGES_FILE), URL_SERVER + ProjectResources.STAGES_FILE);
                publishProgress(50);
                res.loadStages();
                publishProgress(60);
                downloader.dowloadFile(new File(appDir, ProjectResources.BANDS_FILE), URL_SERVER + ProjectResources.BANDS_FILE);
                publishProgress(70);
                res.loadBands();
                publishProgress(80);
                downloader.dowloadFile(new File(appDir, ProjectResources.SHOWS_FILE), URL_SERVER + ProjectResources.SHOWS_FILE);
                publishProgress(90);
                res.loadShows();
                publishProgress(100);
                return true;
            } catch (ConfigurationException e) {
                return false;
            } catch (IOException e) {
                return false;
            } catch (ParserException e) {
                return false;
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            activity.mProgressDialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            activity.tryDismissDialog(0);
            if (result) {
                activity.successTask();
            } else {
                activity.errorTask();                
            }
        }
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setup);
        if (task != null && task.getStatus() == Status.RUNNING && !task.isCancelled()) {
            // La tarea se está ejecutando, le decimos que estamos aquí
            task.setActivity(this);
        } else {
            // No estamos conectados ni nada, empezamos
            setContentView(R.layout.setup);
            Button button = (Button) findViewById(R.id.start_button);
            button.setOnClickListener(new OnClickListener() {            
                @Override
                public void onClick(View arg0) {
                    startTask();
                }
            });
            
            button = (Button) findViewById(R.id.about_button);
            button.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    showAbout();
                }
            });
            button = (Button) findViewById(R.id.exit_button);
            button.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    finish();
                }
            });
        }
    } 

    protected void successTask() {
        startActivity(new Intent(this, MainActivity.class));
    }

    protected void errorTask() {
        Toast.makeText(this, "ERROR!", Toast.LENGTH_SHORT).show();
    }

    protected void startTask() {
        task = new SetupTask();
        task.setActivity(this);
        task.execute(new Void[0]);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle("Conectando");
        mProgressDialog.setMessage("Extrayendo los datos del servidor");
        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {            
            @Override
            public void onCancel(DialogInterface dialog) {
                if (task!=null && task.getStatus()==Status.RUNNING && !task.isCancelled()) {
                    task.cancel(true);
                }
            }
        });
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        return mProgressDialog;
    } 
    
    protected void tryDismissDialog(int id) {
        try {
            dismissDialog(id);      
        } catch (Exception e) {
            // No hay problema
        }
    }
    
    protected void showAbout() {
        Context context = getApplicationContext();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name));
        builder.setIcon(R.drawable.icon);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        View about = inflater.inflate(R.layout.about, null);
        builder.setView(about);
        builder.setPositiveButton("OK", null);
        builder.create();
        builder.show();
    }

}
